package com.xhtranslate.common.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

/**
 * 文件操作工具类
 */
@Component
public class FileUtil {
    @Value("${spring.servlet.multipart.location}")
    private String realPath;

    /**
     * 保存图片至服务器
     *
     * @param file
     * @throws IOException
     */
    public File saveImg(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String now = System.currentTimeMillis() + "__";
        String s = now + filename;
        String tmpfile = realPath + "//" + s;
        File file2 = new File(tmpfile);
        file.transferTo(file2);
        return file2;
    }

    /**
     * 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
     *
     * @param imgFile
     * @return
     */
    public String imgToBase64(String imgFile) {
        File file = new File(imgFile);
        if (!file.exists()) {
            return null;
        }
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        return Base64.getEncoder().encodeToString(data);
    }

    /**
     * 将MultipartFile转换为File
     *
     * @param multiFile
     * @return
     */
    public static File MultipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若须要防止生成的临时文件重复,能够在文件名后添加随机码

        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getRealPath() {
        return realPath;
    }

    public void setRealPath(String realPath) {
        this.realPath = realPath;
    }
}
